package com.xiangty.test;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 工具类
 */
public class MyBatisUtil {
	/**
	 * 禁止外界通过new方法创建
	 */
	private MyBatisUtil() {
	}

	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

	private static SqlSessionFactory sqlSessionFactory;

	/**
	 * 加载位于src/mybatis-config.xml配置文件
	 */
	static {
		try (Reader reader = Resources.getResourceAsReader("mybatis-config.xml");) {
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	/**
	 * 获取SqlSession对象
	 * 
	 * @return
	 */
	public static SqlSession getSqlSession() {
		// 从当前线程中获取SqlSession对象
		SqlSession sqlSession = threadLocal.get();
		// 如果SqlSession对象为空
		if (sqlSession == null) {
			// 在SqlSessionFactory非空的情况下，获取SqlSession对象
			sqlSession = sqlSessionFactory.openSession();
			// 将SqlSession对象与当前线程绑定在一起
			threadLocal.set(sqlSession);
		}
		// 返回SqlSession对象
		return sqlSession;
	}

	/**
	 * 关闭SqlSession对象
	 */
	public static void closeSqlSession() {
		// 从当前线程中获取SqlSession对象
		SqlSession sqlSession = threadLocal.get();
		// 如果SqlSession对象非空
		if (sqlSession != null) {
			// 关闭SqlSession对象
			sqlSession.close();
			threadLocal.remove();
		}
	}

	public static void main(String[] args) {
		Connection conn = MyBatisUtil.getSqlSession().getConnection();
		System.out.println(conn != null ? "测试连接成功！" : "测试连接失败！");
	}
	
}
